package com.example.blog.service.impl;

import com.example.blog.dao.UserDao;
import com.example.blog.dto.UserDTO;
import com.example.blog.pojo.User;
import com.example.blog.service.UserService;
import com.example.blog.utils.AliyunOssUtil;
import com.example.blog.utils.Md5Util;
import com.example.blog.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private AliyunOssUtil aliyunOssUtil;
    @Override
    public User findByUserName(String username) {

        User user = userDao.findByUserName(username);
        return user;

    }

    @Override
    public User findByUserId(Integer id) {

        User user = userDao.findById(id);
        return user;

    }

    @Override
    public boolean updateUser(String nickname, String signature, String email) {

        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        Integer n = userDao.updateUser(id,nickname,signature,email,LocalDateTime.now());
        if(n>0)return true;
        else return false;

    }

    @Override
    public boolean register(String username, String password, String nickname, LocalDateTime createtime, LocalDateTime updatetime) {

        String md5String = Md5Util.getMD5String(password);
        String avatar = "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png";
        Integer n = userDao.addUser(username,md5String,nickname,createtime,updatetime,0,avatar);
        if(n>0)return true;
        else return false;

    }

    @Override
    public boolean updatePwd(String newPwd) {
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        Integer n = userDao.updatePwd(id,Md5Util.getMD5String(newPwd));
        if(n>0)return true;
        else return false;
    }

    @Override
    public boolean updateAvatar(String url) {

        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        //更新url之前,将原文件删除
        User user = userDao.findById(id);
        String oldurl = user.getAvatarurl();
        if(oldurl != null){
            aliyunOssUtil.delete(oldurl);
        }

        Integer n = userDao.updateAvatarurl(id,url,LocalDateTime.now());
        if (n>0)return true;
        else return false;

    }

    @Override
    public UserDTO findByotherId(Integer id) {
        UserDTO user = userDao.findUserById(id);
        return user;
    }
}
